#include "mockserver.h"

using namespace apollo;
using namespace apollo::core;
MockServer::MockServer(QObject *parent)
	: QTcpServer(parent)
{

}

MockServer::~MockServer()
{

}
void MockServer::deleteThread(QThread *thread)
{
	QLOG_INFO() << "Deleting thread:" ;
	int retry = 0;
	while(thread->isFinished() == false)
	{
		thread->wait(200);
		retry++;
	}
	if(thread->isFinished())
	{
		delete thread;
		QLOG_INFO() << "Deleted thread:" ;
	}
	else
	{
		QLOG_INFO() << "Can not delete thread:" ;
	}
}
void MockServer::incomingConnection(int handle)
{
	 MockServerHandler *thread = new MockServerHandler(handle);
	 connect(thread, SIGNAL(error(QString, int,QTcpSocket::SocketError)), this, SLOT(error(QString, int,QTcpSocket::SocketError)));
     connect(thread, SIGNAL(finishedThread(QThread*)), this, SLOT(deleteThread(QThread*)));
	 thread->moveToThread(thread);
	 
     thread->start();
	 QLOG_INFO() << "starting handler thread. current thread id in mock server: " << QThread::currentThreadId();
	 /*
	 if(thread->wait(2000) == false)
	 {		 
		QCoreApplication::postEvent(thread, new AnyEvent("Hello", 5));
		std::cout << "current thread id in mock server: " << QThread::currentThreadId() << std::endl;
	 }*/

	 
  //   thread->start();
	 //if(thread->wait(2000) == false)
	 //{		 
		////thread->sendEvent(new AnyEvent("Hello", 5));
		// thread->write("Hello", 5);
		//std::cout << "current thread id in mock server: " << QThread::currentThreadId() << std::endl;
	 //}
}

void MockServer::error(QString ip, int port,QTcpSocket::SocketError error)
{
	QLOG_INFO() << "From IP: " << ip << ", Port: " << port << "Error: " << error;
}
